<template>
  <model-dialog
    title="同步至微信素材库"
    :visible.sync="dialogVisible"
    :show-close="false"
    @close="dialogVisible=!dialogVisible">
    <el-form
      ref="dataForm"
      :rules="contentSyncWxPubRules"
      :model="contentSyncWxPubRecord"
      label-position="right"
      label-width="60px">
      <el-form-item label="文章:">{{ contentSyncWxPubRecord.title }} </el-form-item>
      <el-form-item label="应用:" prop="appId">
        <application-key-select v-model="contentSyncWxPubRecord.appId" :type="1" style="width: 100%;" />
      </el-form-item>
      <el-form-item label="分类:" prop="category">
        <el-select-tree v-model="contentSyncWxPubRecord.category" :data="categories" :props="{children: 'children', label: 'name'}" />
      </el-form-item>
    </el-form>
    <template slot="footer">
      <el-button type="primary" plain @click="handleSyncMaterialLibrary">同步</el-button>
    </template>
  </model-dialog>
</template>
<script>
import applicationKeySelect from '@/views/third/applicationKeySelect.vue'
export default {
  components: { applicationKeySelect },
  data() {
    return {
      dialogVisible: false,
      categories: [],
      contentSyncWxPubRecord: {},
      contentSyncWxPubRules: {
        appId: [
          { required: true, message: '请选择微信公众号应用', trigger: 'blur' }
        ],
        category: [
          { required: true, message: '请选择素材分类', trigger: 'blur' }
        ]
      }
    }
  },
  watch: {
    'contentSyncWxPubRecord.appId': function(val) {
      this.fetchCategories()
    }
  },
  methods: {
    init(params = { id: null, title: null }) {
      this.dialogVisible = true
      this.contentSyncWxPubRecord = {
        ...this.contentSyncWxPubRecord,
        id: params.id,
        title: params.title
      }
    },
    async fetchCategories() {
      var res = await this.$store.dispatch('thirdWechatResourceCategoryTree', { appId: this.contentSyncWxPubRecord.appId, type: '4' })
      this.categories = res
    },
    handleSyncMaterialLibrary() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          this.$store.dispatch('contentArticleSyncWxPub', this.contentSyncWxPubRecord).then(response => {
            this.$modal.msgSuccess('同步成功!')
            this.dialogVisible = false
            this.$emit('success', true)
          }).catch(() => {
          })
        }
      })
    }
  }
}
</script>
